package com.eric.r2d2.urlbase;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;

public class GetRoot {

	public static void main(String[] args) throws IOException {
		String s = args[0];
		File file = new File(s);
		if (file.exists()) {
			BufferedReader br = new BufferedReader(new FileReader(file));
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file.getAbsolutePath()+".root")));
			String line;
			while ((line = br.readLine()) != null) {
				JSONObject json = null;
				
				try {
					json = (JSONObject) JSONObject.parseObject(line);
				}catch ( com.alibaba.fastjson.JSONException e) {
				}
				
				if (json != null ) {
					System.out.println(getRoot(json.getString("url")));
					bw.append(getRoot(json.getString("url")));
					bw.append("\n");
				}else{
					System.out.println(getRoot(line));
					bw.append(getRoot(line));
					bw.append("\n");
				}
				
			}
			br.close();
			bw.close();
		}else{
			System.out.println(getRoot(s));
		}
	}
	public static String getRoot (String url) throws MalformedURLException {
    	URL u = new URL(url);
    	String host = u.getHost();
    	StringBuffer root = new StringBuffer();
    	String[] rootMembers = host.split("\\.");
    	
    	//一般情况下，取host的最后2个，如www.abc.com取abc.com
    	int n = 2;
    	
    	//判断后缀是否超过1个，比如edu.cn
    	if (rootMembers.length > 2 ) {
    		//域名最后一个后缀和倒数第二个后缀
    		String lastMember = rootMembers[rootMembers.length - 1];
    		String secondLastMember = rootMembers[rootMembers.length - 2];
    		
    		//如果最后一个后缀是.com，则n取2（以防误中类似“123.abc.def.com”）
    		if (lastMember.matches("^com$|^org$|^net$")) {
    			n=2;
    		}
    		//如果最后一个是国家域名（这里只考虑.cn，后续可以把所有国家后缀考虑进来
    		else if (lastMember.matches("^cn$|^cc$")) {
    			//类似"abc.com.cn"形式的，n取值3
    			if (secondLastMember.matches("^com$|^net$|^gov$|^edu$")) 
    				n = 3;
    			else
    				n = 2;
    		}
    		else{
    			n = 3;
    		}
    	}
    	
    	for (int i=n;i>0;i--){
    		//if (host.split("\\.").length > 1) 
    		try {
    			root.append(host.split("\\.")[host.split("\\.").length-i]);
        		if ((i-1) > 0)root.append(".");
    		}catch (java.lang.ArrayIndexOutOfBoundsException e) {
    			System.out.println("Wrong Url:"+url);
    		}
    	}
    	
    	return root.toString();
    }
}
